
cat_sub_path='Testas-X'

def set_cat_sub_path( new ):
    global cat_sub_path
    cat_sub_path = new
    __print_category("")
    
def __print_category(cat_name):
    if cat_sub_path:  cat_name = cat_sub_path+'/'+cat_name
    cat_name = cat_name.rstrip('/')
    print("\n\n$CATEGORY: $system$/%s\n" %  cat_name )
    
    
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
    
import sys

class CaptureOut(list):          #http://stackoverflow.com/a/16571630
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout
        


def generate_calls(**kwargs):
    def generated_calls(func):
        def func_wrapper():
            if 'groups' in kwargs:
                groups = kwargs.pop('groups')
            else:
                groups = ["",  len(list(kwargs.items())[0][1] )  ] # take the length of any group  
                
            start = 0
            # example: groups = ["less", 3, "equal", 0, "more", 3] -- take by pairs:
            for group, count  in [ (groups[i:i+2]) for i in range(0, len(groups), 2)]:
                #print(group, count)
                if group or count>1:
                    cat_name =  func.__name__
                    if group:  cat_name += "/"+group
                    __print_category(  cat_name )                
                # args for one call
                for k in range(start, start+count):
                    args_instance = {argname:argvals[k] for argname, argvals in kwargs.items() }

                    out = generate_question_by_call( func, name_extra=group, **args_instance ) ## print question
                    
                start += count
                
        return func_wrapper
    return generated_calls

#~ from helpers import src_to_GIFT 
import helpers
import inspect
import re

#outfile = open('out.txt', 'w')

def generate_question_by_call( func, name_extra="", **args_instance ):
    #~ print( func.__name__, args_instance )
    
    ###### prepair Question
    
    def code_src():  # TODO - put in helpers
        #~ from pprint import pprint
        func_src = inspect.getsource(func)
        results = re.split( r'(def\s+{}[^:]+):'.format( func.__name__ ) , func_src, maxsplit=1)
        decorator, prototype, src = results 
        for name, val in args_instance.items():  # inject actual arg values
            if name.startswith('_'):
                re_param = re.compile(r'\b%s\b'%name)
                src = re.sub(re_param, repr(val), src )    
                prototype = re.sub(re_param, repr(val), prototype )   
        return prototype, src
        
    prototype, src = code_src()
    prototype = prototype[len("def "):].strip(' \t') # get rid of word "def"
    if name_extra:
        prototype = prototype.replace(func.__name__, func.__name__+"__"+name_extra)

    
    question = (helpers.src_to_GIFT(
                    prototype, # title
                    #~ strip_first_line(src),          
                    helpers.code2pygmetshtml(src, 'py' , inlineCSS=True) ,# src
                    #~ f_args, f_locals, CONVERT2CPP
                    question_text="Ką atspausdins (atskirkite tarpais)?", 
                    markup_type="html",
          )
    )

    ###### prepair Answer
    # call the function
    with CaptureOut() as output:
         func( **args_instance )  
             
    answer = ' '.join(  output ).rstrip('\n\t ')
    answer = "{=%s} " % helpers.escape_GIFT_spec_chars(answer)

    print  ("\n\n" + question + answer ) 
    return ("\n\n" + question + answer ) 

#################
def call_functions_by_decorators(fun_dict, outfile=None):
    
    import inspect
    
    decorated_functions = [x for x in fun_dict.values() if inspect.isfunction(x)  
                           and str(x).startswith('<function generate_calls.') ]
    
    Questions = []
    for func in decorated_functions:
        with CaptureOut() as output:
            func()
        Questions.append( '\n'.join(output) )
        

    for q in Questions:
        print("\n"*5, q)
        #~ print( q[200:]+"..."+q[:200] )

    if outfile:
        with open(outfile, 'w', encoding="utf-8") as f:
            f.write(("\n"*5).join( Questions ) )
    
 
